from pydantic import BaseModel, EmailStr, validator, Field
from typing import Optional
from database.models import UserRole


class UserCreate(BaseModel):
    """用户创建验证器"""
    email: EmailStr
    username: str
    password: str
    full_name: Optional[str] = None
    phone: Optional[str] = None
    role: UserRole = UserRole.CUSTOMER
    
    @validator('username')
    def validate_username(cls, v):
        if len(v) < 3:
            raise ValueError('用户名长度至少3个字符')
        if len(v) > 50:
            raise ValueError('用户名长度不能超过50个字符')
        if not v.isalnum() and '_' not in v:
            raise ValueError('用户名只能包含字母、数字和下划线')
        return v
    
    @validator('password')
    def validate_password(cls, v):
        if len(v) < 6:
            raise ValueError('密码长度至少6个字符')
        return v
    
    @validator('phone')
    def validate_phone(cls, v):
        if v and not v.isdigit():
            raise ValueError('手机号只能包含数字')
        if v and len(v) != 11:
            raise ValueError('手机号长度必须为11位')
        return v


class UserUpdate(BaseModel):
    """用户更新验证器"""
    email: Optional[EmailStr] = None
    full_name: Optional[str] = None
    phone: Optional[str] = None
    role: Optional[UserRole] = None
    is_active: Optional[bool] = None
    avatar_url: Optional[str] = None
    
    @validator('phone')
    def validate_phone(cls, v):
        if v and not v.isdigit():
            raise ValueError('手机号只能包含数字')
        if v and len(v) != 11:
            raise ValueError('手机号长度必须为11位')
        return v


class UserLogin(BaseModel):
    """用户登录验证器"""
    username: str
    password: str


class UserResponse(BaseModel):
    """用户响应模型"""
    id: int
    email: str
    username: str
    full_name: Optional[str]
    phone: Optional[str]
    role: UserRole
    is_active: bool
    avatar_url: Optional[str]
    created_at: str
    updated_at: Optional[str] = None
    
    class Config:
        from_attributes = True
        
    @validator('created_at', 'updated_at', pre=True)
    def format_datetime(cls, v):
        """将datetime对象格式化为字符串"""
        if v is None:
            return None
        if hasattr(v, 'isoformat'):
            return v.isoformat()
        return str(v)


class Token(BaseModel):
    """JWT令牌响应模型"""
    access_token: str
    token_type: str
    user_id: int
    username: str
    role: str


class UserPasswordChange(BaseModel):
    """用户密码修改验证器"""
    old_password: str
    new_password: str
    
    @validator('new_password')
    def validate_new_password(cls, v):
        if len(v) < 6:
            raise ValueError('新密码长度至少6个字符')
        return v